package services;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.CommentRepository;
import domain.Administrator;
import domain.Comment;
import domain.Customer;
import domain.Painting;

@Service
@Transactional
public class CommentService {

	@Autowired
	private CommentRepository commentRepository;
	@Autowired
	private PaintingService paintingService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private AdministratorService administratorService;

	public CommentService() {
		super();
	}

	public Comment create(int paintingId) {
		Comment comment;
		Painting painting;
		Customer customer;

		comment = new Comment();
		painting = paintingService.findOne(paintingId);
		customer = customerService.findByPrincipal();
		comment.setCreationMoment(new Date());

		comment.setPainting(painting);
		comment.setCustomer(customer);
		return comment;
	}

	public void save(Comment comment) {
		Assert.notNull(comment);
		Assert.isTrue(comment.getCustomer().equals(
				customerService.findByPrincipal()));
		Assert.isTrue(!comment.getText().isEmpty());
		commentRepository.save(comment);

	}

	public Collection<Comment> findByMoreResponses() {
		Collection<Comment> res;
		Administrator principal;
		principal = administratorService.findByPrincipal();
		Assert.isTrue(principal instanceof Administrator);
		res = commentRepository.findByMoreResponses();
		return res;

	}

	public Collection<Comment> findByPainting(int idPainting) {
		Collection<Comment> res;
		res = commentRepository.findByPainting(idPainting);
		return res;

	}

	public Comment findOne(int commentId) {
		Comment res;

		res = commentRepository.findOne(commentId);

		return res;
	}

}
